﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using MineBoxRelease.Model;
using MineBoxRelease.View;

namespace MineBoxRelease.Core.View.Creator
{
    class AppBoxViewCreator : IViewCreator
    {
        public BaseView Create(XmlElement root)
        {
            AppBoxView view;
            try
            {
                string tabTitle = root.GetAttribute("title");
                XmlNodeList nodes = root.GetElementsByTagName("app");
                List<Shortcut> list = new List<Shortcut>();
                foreach (XmlNode node in nodes)
                {
                    string title = node.Attributes["title"].InnerText;
                    string path = node.Attributes["path"].InnerText;
                    if (File.Exists(path))
                        list.Add(new Shortcut(title, path));
                }
                view = new AppBoxView(tabTitle);
                view.SetShortcuts(list);
            }
            catch (Exception)
            {
                throw;
            }
            return view;
        }

        public BaseView Create(string title = null)
        {
            if (title == null || title.Equals("")) title = "应用盒子";
            return new AppBoxView(title);
        }

        public void Save(BaseView view, string path)
        {
            try
            {
                AppBoxView v = view as AppBoxView;
                List<Shortcut> list = v.GetShortcuts();
                XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                /*根节点*/
                writer.WriteStartElement("viewxml");
                writer.WriteAttributeString("title", v.Title);
                writer.WriteAttributeString("type", "AppBox");

                foreach (Shortcut shortcut in list)
                {
                    writer.WriteStartElement("app");
                    writer.WriteAttributeString("title", shortcut.Title);
                    writer.WriteAttributeString("path", shortcut.FilePath);
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
